from flask import Flask, request, jsonify, Blueprint
from models import db, Course, Class, Student, Enrollment, Grade

api = Blueprint('api', __name__)
# 成绩管理
@api.route('/grades', methods=['POST'])
def record_grade():
    data = request.json
    new_grade = Grade(student_id=data['student_id'], class_id=data['class_id'], grade=data['grade'])
    db.session.add(new_grade)
    db.session.commit()
    return jsonify({'message': 'Grade recorded'})

@api.route('/grades/query', methods=['GET'])
def query_grades():
    class_id = request.args.get('class_id')
    semester = request.args.get('semester')
    if class_id:
        grades = Grade.query.filter_by(class_id=class_id).all()
    elif semester:
        grades = Grade.query.join(Class).filter(Class.semester == semester).all()
    return jsonify([{
        'student_id': g.student_id, 
        'class_id': g.class_id, 
        'grade': g.grade
    } for g in grades])

@api.route('/grades', methods=['GET'])
def get_grades():
    grades = db.session.query(Grade, Student, Class, Course).join(
        Student, Grade.student_id == Student.student_id
    ).join(
        Class, Grade.class_id == Class.class_id
    ).join(
        Course, Class.course_id == Course.course_id
    ).all()
    
    result = []
    for grade, student, class_obj, course in grades:
        result.append({
            'id': f"{grade.student_id}_{grade.class_id}",
            'student_id': student.student_id,
            'student_name': student.student_name,
            'class_id': class_obj.class_id,
            'class_name': class_obj.class_name,
            'course_name': course.course_name,
            'semester': class_obj.semester,
            'grade': grade.grade
        })
    
    return jsonify(result)


@api.route('/grades/students/<int:student_id>', methods=['GET'])
def get_student_grades(student_id):
    grades = db.session.query(Grade, Class, Course).join(
        Class, Grade.class_id == Class.class_id
    ).join(
        Course, Class.course_id == Course.course_id
    ).filter(Grade.student_id == student_id).all()
    
    result = []
    for grade, class_obj, course in grades:
        result.append({
            'class_id': class_obj.class_id,
            'class_name': class_obj.class_name,
            'course_name': course.course_name,
            'semester': class_obj.semester,
            'grade': grade.grade
        })
    
    return jsonify(result)